<?php

namespace tbollmeier\kakuromaster\core;

class Set
{
    public function __construct($elements=[])
    {
        $this->elements = [];
        
        foreach($elements as $elem) {
            $this->add($elem);
        }
    }
    
    public function intersection(Set $other)
    {
        $intersection = new Set();
        foreach (array_keys($this->elements) as $element) {
            if ($other->contains($element)) {
                $intersection->add($element);
            }
        }
        
        return $intersection;
    }
    
    public function union(Set $other)
    {
        $union = new Set($this->elements);
        $union->add(array_keys($other->elements));
        
        return $union;
    }
    
    public function add($el)
    {
        if (!is_array($el)) {
            $this->elements[$el] = true;
        } else {
            foreach ($el as $item) {
                $this->elements[$item] = true;
            }
        }
    }
    
    public function contains($el)
    {
        return array_key_exists($el, $this->elements);
    }
    
    public function toArray()
    {
        $res = array_keys($this->elements);
        sort($res);
        
        return $res;
    }
    
    public function __toString()
    {
        $res = "";
        
        $elements = $this->toArray();
        foreach ($elements as $el) {
            if (!empty($res)) {
                $res .= ", ";
            }
            $res .= $el;
        }
        
        $res = "#{" . $res . "}";
        
        return $res;
    }
    
    private $elements;
}
